#include "software.h"

Mat src, hsv, dst;
Mat element;
vector<int>upper(3, 255);
vector<int>lower(3.0);
vector<vector<Point>>contours;
vector<vector<Point>>max_contours;
vector<Vec4i>hierarchy;

double area = 0, temp_area = 0;
int index = 0, h, w;
Point2f center;
float radius;

int tracker(int g_upper_h, int g_upper_s, int g_upper_l, int g_lower_h, int g_lower_s, int g_lower_l)
{
	

	upper = { g_upper_h,g_upper_s,g_upper_l };

	lower = { g_lower_h,g_lower_s,g_lower_l };

	element = getStructuringElement(MORPH_RECT, Size(5, 5));		//Obtain the mask for erode and dilate

	src = imread(path);

	h = src.rows;
	w = src.cols;
	resize(src, src, Size(640, 480), w / 640, h / 480);

	if (!src.data)
	{
		printf("camera is not opened.\n");
		return -1;
	}

	namedWindow("tracking figure");
	namedWindow("original figure");

	imshow("tracking figure", src);
	imshow("original figure", src);


	cvtColor(src, hsv, COLOR_BGR2HLS);
	inRange(hsv, lower, upper, dst);

	erode(dst, dst, element);		//erode for white
	dilate(dst, dst, element);		//dilate

	findContours(dst, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);		//Find the outline

	for (int i = 0; i < contours.size(); i++)		//Find the max outline
	{
		temp_area = contourArea(contours[i]);
		if (temp_area >= area)
		{
			index = i;
			area = temp_area;
		}

	}


	if (contours.size() > 0)
	{
		minEnclosingCircle(contours[index], center, radius);		//Calculate the smallest enclosing circle
		circle(src, center, (int)radius, Scalar(0, 0, 255), 3);		//Draw a circle in the original image
		cout << "X:" << center.x << endl;
		cout << "Y:" << center.y << endl;
		cout << "radius:" << radius << endl;
	}

	imshow("original figure", src);
	imshow("tracking figure", dst);

	waitKey(0);
	return 0;
}